package cn.spring.starter.lock.core;

import com.google.common.base.Preconditions;
import cn.spring.starter.lock.config.RedissonProperties;
import cn.spring.starter.lock.constant.RedisConnectionType;
import cn.spring.starter.lock.core.stragety.*;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.config.Config;

/**
 * @author xingkong
 * @Title: RedissonManager
 * @Description: Redisson配置管理器，用于初始化的redisson实例
 * @date 2021/10/27 17:39
 */
@Slf4j
public class RedissonManager {
    private Config config = new Config();

    private Redisson redisson = null;

    public RedissonManager() {
    }

    public RedissonManager(RedissonProperties properties) {
        //装配开关
        Boolean enabled = properties.getEnabled();
        if (enabled) {
            try {
                config = RedissonConfigFactory.getInstance().createConfig(properties);
                redisson = (Redisson) Redisson.create(config);
            } catch (Exception e) {
                log.error("Redisson初始化错误", e);
            }
        }
    }

    public Redisson getRedisson() {
        return redisson;
    }

    /**
     *Redisson连接方式配置工厂
     */
    static class RedissonConfigFactory{
        private RedissonConfigFactory() {

        }

        private static volatile RedissonConfigFactory factory = null;

        public static RedissonConfigFactory getInstance() {
            if (factory == null) {
                synchronized (Object.class) {
                    if (factory == null) {
                        factory = new RedissonConfigFactory();
                    }
                }
            }
            return factory;
        }

        Config createConfig(RedissonProperties redissonProperties) {
            Preconditions.checkNotNull(redissonProperties);
            Preconditions.checkNotNull(redissonProperties.getAddress(), "redisson地址未配置");
            RedisConnectionType connectionType = redissonProperties.getType();
            //申明连接方式
            RedissonConfigStrategy redissonConfigStrategy = null;

            switch (connectionType) {
                case SENTINEL:
                    redissonConfigStrategy = new SentinelRedissonConfigStrategyImpl();
                    break;
                case CLUSTER:
                    redissonConfigStrategy = new ClusterRedissonConfigStrategyImpl();
                    break;
                case MASTERSLAVE:
                    redissonConfigStrategy = new MasterslaveRedissonConfigStrategyImpl();
                    break;
                case STANDALONE:
                    redissonConfigStrategy = new StandaloneRedissonConfigStrategyImpl();
                    break;
                default:
                    throw new RuntimeException("不存在该部署方式");
            }
            return redissonConfigStrategy.createRedissonConfig(redissonProperties);
        }
    }
}
